package com.github.cyf.redisson;

import com.github.cyf.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author chenyifan
 * @create 2025-05-26 17:21
 */
@Service
@Slf4j
public class RedissonService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ThreadPoolTaskExecutor threadPool;

    public void reduceStock() {
        //对数据进行加锁
        RLock lock = redissonClient.getLock("product");
        redisUtil.set("stock", 5);
        //加锁
        for (int i = 0; i < 10; i++) {
            threadPool.execute(() -> {
                boolean isSuccess;
                try {
                    isSuccess = lock.tryLock(10, 4, TimeUnit.SECONDS);
                    if (!isSuccess) {
                        log.info("获取锁失败");
                        return;
                    }
                    log.info("获取锁成功");
                    Integer stock = (Integer) redisUtil.get("stock");
                    if (stock > 0) {
                        //下单
                        stock -= 1;
                        redisUtil.set("stock", stock);
                        log.info("扣减成功，库存stock：{}",  stock);
                        Thread.sleep(500);
                    } else {
                        //没库存
                        log.info("扣减失败，库存不足");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                        lock.unlock();
                    }
                }
            });
        }
    }
}